package org.example.lanhang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageSerializable;
import org.example.lanhang.entity.TUser;
import org.example.lanhang.entity.TUserExample;
import org.example.lanhang.mapper.TUserMapper;
import org.example.lanhang.service.userService;
import org.example.lanhang.uservo.uservo;
import org.example.lanhang.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class userServiceimpl implements userService {

    @Autowired
    private TUserMapper tUserMapper;

    @Override
    public List<TUser>findall(){
        return tUserMapper.selectByExample(null);
    }


    @Override
    public PageResult<TUser> findByPage(Integer page, Integer pageSize) {
        //1. 开始分页
        PageHelper.startPage(page,pageSize);
        // 2. 开始查询数据
        List<TUser> students = this.findall();
        // 3. 将查询得到的数据转换为Page<Student>对象
        Page<TUser> userPage = (Page<TUser>) students;
        // 4. 转换为PageResult对象
        return new PageResult<>(userPage.getResult(),userPage.getTotal());

    }

    @Override
    public PageResult<TUser> search(Integer page, Integer pageSize, uservo uservo) {
            // 1. 开始分页
            PageHelper.startPage(page, pageSize);
            // 2. 查询数据
            // 2.1 定义一次查询的实例
            TUserExample example = new TUserExample();
            // 2.2 添加查询条件到查询实例中
            TUserExample.Criteria criteria = example.createCriteria();
            if(StrUtil.isNotBlank(uservo.getName())){
                criteria.andNameLike("%" + uservo.getName() + "%");
            }
            if(uservo.getAge() != null && uservo.getAge()!=0){
                criteria.andAgeEqualTo(uservo.getAge());
            }
            List<TUser> users = tUserMapper.selectByExample(example);


            Page<TUser> userPage = (Page<TUser>) users;
            return new PageResult<>(userPage.getResult(),userPage.getTotal());


    }

    // 3. 添加学生
    public boolean save(TUser tUser) {
        return tUserMapper.insert(tUser) > 0;
    }

}
